package com.waimai.demo.Service.Serviceimpl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.waimai.demo.Dao.DishMapper;
import com.waimai.demo.Service.DishFlavorService;
import com.waimai.demo.Service.DishService;
import com.waimai.demo.back.R;
import com.waimai.demo.domain.Dish;
import com.waimai.demo.domain.DishFlavor;
import com.waimai.demo.dto.DishDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
@Transactional
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {
    @Autowired
    private DishFlavorService dishFlavorService;

    public void savawithflavor(DishDto dishDto, Long ids) {
        dishDto.setCreateTime(LocalDateTime.now());
        dishDto.setUpdateTime(LocalDateTime.now());
        dishDto.setCreateUser(ids);
        dishDto.setUpdateUser(ids);
        System.out.println("=======李兴建你奶奶的===========" + dishDto.toString());
        this.save(dishDto);
        Long dishId = dishDto.getId();
        List<DishFlavor> list = dishDto.getFlavors();

        for (DishFlavor dishFlavor : list) {
            dishFlavor.setDishId(dishId);
            dishFlavor.setCreateTime(LocalDateTime.now());
            dishFlavor.setUpdateTime(LocalDateTime.now());
            dishFlavor.setCreateUser(ids);
            dishFlavor.setUpdateUser(ids);
        }
        dishFlavorService.saveBatch(list);
    }//回显操作

    public DishDto updatewithflavor(Long id) {
        Dish dish = this.getById(id);
        LambdaQueryWrapper<DishFlavor> lambdaQueryWrapper = new LambdaQueryWrapper();
        lambdaQueryWrapper.eq(DishFlavor::getDishId, dish.getId());
        List<DishFlavor> list = dishFlavorService.list(lambdaQueryWrapper);
        DishDto dishDto = new DishDto();
        BeanUtils.copyProperties(dish, dishDto);
        dishDto.setFlavors(list);
        System.out.println("===========================你妈的比" + dishDto.toString());
        return dishDto;
    }//修改操作

    public void removewithflavor(DishDto dishDto) {
        this.updateById(dishDto);
        LambdaQueryWrapper<DishFlavor> lambdaQueryWrapper = new LambdaQueryWrapper();
        lambdaQueryWrapper.eq(DishFlavor::getDishId, dishDto.getId());
        dishFlavorService.remove(lambdaQueryWrapper);
        List<DishFlavor> flavors = dishDto.getFlavors();
        for (DishFlavor flavor : flavors) {
            flavor.setDishId(dishDto.getId()
            );
        }
        dishFlavorService.saveBatch(flavors);
    }


}
